package cn.itsource.system.service.impl;

import cn.itsource.system.domain.Role;
import cn.itsource.system.mapper.RoleMapper;
import cn.itsource.system.service.IRoleService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public void add(Role role) {
        //添加角色
        super.add(role);
        //添加角色权限
        if (role.getPermissions() != null && role.getPermissions().size() > 0){
            roleMapper.rolePermissions(role);
        }
        //添加菜单
        if (role.getMenus() != null && role.getMenus().size() > 0){
            roleMapper.roleMenus(role);
        }
    }

    @Override
    public void delete(Long id) {
        //先删除中间表的数据，再删除角色表的数据
        roleMapper.deleteRolePermissions(id);
        roleMapper.deleteRoleMenus(id);
        super.delete(id);
    }

    @Override
    public void batchDelete(List<Long> ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    @Override
    public void update(Role role) {
        //修改角色
        super.update(role);
        //先删除再添加
        roleMapper.deleteRolePermissions(role.getId());
        roleMapper.deleteRoleMenus(role.getId());
        //添加角色权限
        if (role.getPermissions() != null && role.getPermissions().size() > 0){
            roleMapper.rolePermissions(role);
        }
        //添加菜单
        if (role.getMenus() != null && role.getMenus().size() > 0){
            roleMapper.roleMenus(role);
        }
    }
}
